package com.geek.gkfood.framework.trace.util;

import org.apache.commons.lang3.StringUtils;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <h1>全局ID生成工具类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-19
 *
 */
public class TraceIdGeneratorUtils {

    /**
     * <h2>获取 traceId，有则用，无则生成（简单粗暴UUID生成，有兴趣的童鞋可以优化成为更为有意义的ID生成）。</h2>
     *
     * @param traceId
     * @return
     */
    public static String getTraceId(String traceId) {
        if (StringUtils.isNotBlank(traceId)) {
            return traceId;
        }

        return getUuid().substring(20) + ThreadLocalRandom.current().nextInt(1000, 9999);
    }

    /**
     * <h2>获取GUID。</h2>
     *
     * @return
     */
    private static String getUuid() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        return uuidStr.toLowerCase();
    }
}